package com.compass.mobile.ui.activity

import LogUtil
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.core.content.ContentProviderCompat.requireContext
import androidx.fragment.app.FragmentTransaction
import com.compass.mobile.R
import com.compass.mobile.databinding.ActivityHomePageBinding
import com.compass.mobile.framework.base.BaseVBActivity
import com.compass.mobile.framework.constant.CANCEL_INVITE
import com.compass.mobile.framework.constant.CLOSE_EVENT
import com.compass.mobile.framework.constant.FLY_HOME_SCENE
import com.compass.mobile.framework.constant.PATIENT_SWITCH
import com.compass.mobile.framework.utils.LiveDataBus
import com.compass.mobile.framework.utils.getAction
import com.compass.mobile.models.MessageModel
import com.compass.mobile.ui.dialog.CommonMessageDialog
import com.compass.mobile.ui.fragment.NewHomePageFragment
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.google.gson.reflect.TypeToken
import com.iflytek.xiri.app.Feedback
import com.iflytek.xiri.scene.ISceneListener
import com.iflytek.xiri.scene.Scene
import com.iflytek.xiri.scene.SceneInfo
import com.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.Observer
import com.netease.nimlib.sdk.avsignalling.SignallingServiceObserver
import com.netease.nimlib.sdk.avsignalling.constant.SignallingEventType
import com.netease.nimlib.sdk.avsignalling.event.CanceledInviteEvent
import com.netease.nimlib.sdk.avsignalling.event.ChannelCloseEvent
import com.netease.nimlib.sdk.avsignalling.event.ChannelCommonEvent
import com.netease.nimlib.sdk.avsignalling.event.ControlEvent
import com.netease.nimlib.sdk.avsignalling.event.InviteAckEvent
import com.netease.nimlib.sdk.avsignalling.event.InvitedEvent
import com.netease.nimlib.sdk.avsignalling.event.UserJoinEvent
import com.netease.nimlib.sdk.avsignalling.event.UserLeaveEvent
import com.netease.nimlib.sdk.msg.MsgServiceObserve
import getStringFromResource
import toJson


/**
 * Description： navigation Main activity
 * Date:2024/5/9 19:29
 */
class HomePageActivity : BaseVBActivity<ActivityHomePageBinding>(),ISceneListener  {

    var tag = "VideoCall:===onlineObserver"

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, HomePageActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        mBinding.topView.setPatientViewVisible(false)
        mBinding.topView.setPatientViewVisible(true)
        val fragmentTransaction: FragmentTransaction = supportFragmentManager.beginTransaction()
//        fragmentTransaction.replace(R.id.fragmentContainer,HomePageFragment() )
        fragmentTransaction.replace(R.id.fragmentContainer, NewHomePageFragment() )
        fragmentTransaction.commit()



        // 切换就诊人需要刷新
        LiveDataBus.get().with(PATIENT_SWITCH, String::class.java) .observe(this) {
            mBinding.topView.setDefaultPatientInfo()
        }


        mScene = Scene(this)
        mFeedback = Feedback(this)

        if (mSceneInfo == null) {
            mSceneInfo = SceneInfo(FLY_HOME_SCENE);
            mSceneInfo?.putKeywords("wz", "在线问诊");
            mSceneInfo?.putKeywords("wzjl", "问诊记录","问诊订单");
            mSceneInfo?.putKeywords("yygh", "预约挂号");
            mSceneInfo?.putKeywords("jzr", "就诊人");
            mSceneInfo?.putKeywords("zzkd", "自主开单");
            mSceneInfo?.putKeywords("tsjy", "投诉建议");
            mSceneInfo?.putKeywords("yy", "预约","预约记录");
            mSceneInfo?.putKeywords("smhl","护理","上门")
            mSceneInfo?.putKeywords("xf","续方","申请续单")
            mSceneInfo?.putKeywords("ys","医生","医师")
        }
    }

    private var mScene : Scene? = null
    private var mFeedback : Feedback? = null

    private var mSceneInfo:SceneInfo? = null
    override fun onResume() {
        super.onResume()
        mScene?.init(this)
    }

    override fun onPause() {
        super.onPause()
        mScene?.release()
    }

    override fun onQuery(): String? {
        return mSceneInfo?.toJson()
    }

    override fun onExecute(intent: Intent?) {
        if(intent == null){
            return
        }

        val command =  intent.getStringExtra("_command");

        val scene = intent.getStringExtra("_scene");

        val rawtext = intent.getStringExtra("_rawtext");
        if(scene == FLY_HOME_SCENE){
            //识别到对应场景
            when(command){
                "wz"->{
                    if (!UserInfoManager.isHaveDefPatient()) {
                        addPatientDialog()
                        showToast("请先添加就诊人")
                        return
                    }
                    //在线问诊
                    DepartmentFragmentActivity.start(this, "inquiry")
                }
                "yygh"->{
                    //预约挂号
                    if (!UserInfoManager.isHaveDefPatient()) {
                        addPatientDialog()
                        showToast("请先添加就诊人")
                        return
                    }
                    DepartmentFragmentActivity.start(this, "booking")
                }
                "jzr"->{
                    //就诊人管理
                    PatientsActivity.start(this)
                }
                "zzkd"->{
                    //自主开单
                    if (!UserInfoManager.isHaveDefPatient()) {
                        addPatientDialog()
                        showToast("请先添加就诊人")
                        return
                    }
                    IndependentBillingActivity.start(this)
                }
                "tsjy"->{
                    //投诉建议
                    if (!UserInfoManager.isHaveDefPatient()) {
                        addPatientDialog()
                        showToast("请先添加就诊人")
                        return
                    }
                    ComplaintActivity.start(this)
                }

                "smhl"->{
                    //上门护理
                    if (!UserInfoManager.isHaveDefPatient()) {
                        addPatientDialog()
                        showToast("请先添加就诊人")
                        return
                    }
                    HomeCareActivity.start(this)
                }

                "yy"->{
                    //我的预约
                    if (!UserInfoManager.isHaveDefPatient()) {
                        addPatientDialog()
                        showToast("请先添加就诊人")
                        return
                    }
                    MyAppointmentActivity.start(this)
                }
                "xf"->{
                    //续方
                    if (!UserInfoManager.isHaveDefPatient()) {
                        addPatientDialog()
                        showToast("请先添加就诊人")
                        return
                    }
                    FollowingPrescriptionActivity.start(this)
                }
                "wzjl"->{
                    if (!UserInfoManager.isHaveDefPatient()) {
                        addPatientDialog()
                        showToast("请先添加就诊人")
                        return
                    }
                    MyOrderActivity.start(this)
                }
                else -> {
                    showToast("暂时无法识别")
                }
            }

        }
//        LogUtil.e("command:${command}, scene:${scene},rawtext:${rawtext}", tag = "ifly")

//        if(){
//
//        }

    }

    private fun addPatientDialog() {
        CommonMessageDialog.Builder(this)
            .setTitle("温馨提示")
            .setMessage("您还没有添加就诊人，是否去添加？")
            .setConfirm(getStringFromResource(R.string.default_confirm))
            .setCancel(getString(R.string.default_cancel))
            .setonCancelListener {
                it?.dismiss()
            }
            .setonConfirmListener {
                PatientsActivity.start(this)
                it?.dismiss()
            }.create().show()
    }

    fun setDefaultPatientView(){
        mBinding.topView.setDefaultPatientInfo()
    }

    private var onlineObserver: Observer<ChannelCommonEvent>? = null
    override fun initData() {

        // 在线通知事件观察者
        onlineObserver = Observer<ChannelCommonEvent> { event: ChannelCommonEvent? ->

            when (event?.eventType) {
                SignallingEventType.CLOSE -> {
                    var channelCloseEvent = event as ChannelCloseEvent

                    LiveDataBus.get().with(CLOSE_EVENT).postValue(channelCloseEvent.channelBaseInfo)
                    LogUtil.d(
                        "频道关闭事件 channelCloseEvent==${channelCloseEvent.toJson()}",
                        tag = tag
                    )
                }

                SignallingEventType.UN_KNOW -> {
                    LogUtil.d("未知事件", tag = tag)
                }

                SignallingEventType.JOIN -> {
                    var userJoinEvent = event as UserJoinEvent

                    LogUtil.d(
                        "有人加入频道事件 userJoinEvent==${userJoinEvent.toJson()}",
                        tag = tag
                    )
                }

                SignallingEventType.INVITE -> {
                    var inviteEvent = event as InvitedEvent

                    //收到邀请
                    VideoAnswerActivity.start(this, inviteEvent)
                    LogUtil.d("被邀请事件  inviteEvent==${inviteEvent.toJson()}", tag = tag)
//                    LogUtil.d("被邀请事件  fromAccountId==${inviteEvent.fromAccountId}", tag = tag)
                }

                SignallingEventType.CANCEL_INVITE -> {
                    var canceledInviteEvent = event as CanceledInviteEvent
                    LiveDataBus.get().with(CANCEL_INVITE).postValue(canceledInviteEvent.channelBaseInfo)
                    LogUtil.d(
                        "取消邀请事件 canceledInviteEvent==${canceledInviteEvent.toJson()}",
                        tag = tag
                    )
                }

                SignallingEventType.REJECT, SignallingEventType.ACCEPT -> {
                    var inviteAckEvent = event as InviteAckEvent


                    LogUtil.d(
                        "对方拒绝/接受 邀请事件 inviteAckEvent===${inviteAckEvent.toJson()}",
                        tag = tag
                    )
                }

                SignallingEventType.LEAVE -> {
                    var userLeaveEvent = event as UserLeaveEvent
                    LogUtil.d(
                        "有用户离开频道事件  userLeaveEvent==${userLeaveEvent.toJson()}",
                        tag = tag
                    )
                }

                SignallingEventType.CONTROL -> {
                    var controlEvent = event as ControlEvent
                    LogUtil.d(
                        "自定义控制命令事件  controlEvent==${controlEvent.toJson()}",
                        tag = tag
                    )
                }

                else -> {
                    LogUtil.d("未知事件", tag = tag)
                }
            }

        }
        NIMClient.getService(SignallingServiceObserver::class.java)
            .observeOnlineNotification(onlineObserver, true)
        initCustomNotification()

    }

    /**
     * 注册云信自定义通知
     */
   private fun initCustomNotification() {
        NIMClient.getService(MsgServiceObserve::class.java).observeCustomNotification({

//                            LogUtil.d("接收到自定义通知：${it.toJson()}" )
            val type = object : TypeToken<MessageModel>() {}.type
            try {
                val messageModel: MessageModel = Gson().fromJson(it.content, type)
//                LogUtil.d("接收到自定义通知：${messageModel.toJson()}" )
                LogUtil.d("消息通知 type===${messageModel.toJson()}")
                messageModel.messageType?.let { type->
//                    initNoticeOfDisposition(getAction(type),messageModel.attach)
                    LiveDataBus.get().with(getAction(type)).postValue(messageModel.attach)
                }
            } catch (e: JsonSyntaxException) {
                   e.printStackTrace()
            }

        }, true)

    }


    override fun onDestroy() {
        super.onDestroy()
        NIMClient.getService(SignallingServiceObserver::class.java)
            .observeOnlineNotification(onlineObserver, false)
    }
}
